package com.wms.security.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wms.plugin.JwtPlugin;
import com.wms.security.MyAuthenticationFailureHandler;
import com.wms.util.UrlUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@Component("adminFilter")
public class AdminFilter extends UrlFilter {

    @Autowired
    private JwtPlugin jwtPlugin;

    @Autowired
    private MyAuthenticationFailureHandler failureHandler;

    @Resource(name = "openFilter")
    public void setUrlFilter(UrlFilter urlFilter) {
        super.setUrlFilter(urlFilter);
    }

    @Override
    public void filter(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String servletPath = request.getServletPath();
        if (servletPath.startsWith("/admin")){
            Claims claims = getClaims(request, jwtPlugin);
            if (claims == null){
                failureHandler.onAuthenticationFailure(request, response, null);
                throw new CredentialsExpiredException("登录失效");
            }

            String subject = claims.getSubject();
            JSONObject subjectObj = JSON.parseObject(subject);
            List<String> authorities = (List<String>) subjectObj.get("authorities");

            boolean bool = authorities.stream().anyMatch(a -> UrlUtil.isMatch(servletPath, a));
            if (!bool){
                failureHandler.onPermissionDenied(request, response, null);
                return;
            }

            request.setAttribute("username", claims.getId());
        }
    }

}
